using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Data;
using System.DirectoryServices;
using EAT.Common;
using System.Configuration;
using System.Web.Security;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebPartPages;
using System.ComponentModel;


namespace ECTSUserMgmtExtension
{
    public class UserManagerExtension : System.Web.UI.WebControls.WebParts.WebPart, IUserManagerUserEditor
    {
        #region AdditionalEmails
        private string m_additionalEmails;
        [WebBrowsable]
        [WebDisplayName("Additional E-Mails")]
        [WebPartStorage(Storage.Shared)]
        [Personalizable(PersonalizationScope.Shared)]
        [Category("Configuration")]
        [DefaultValue("")]
        public string AdditionalEmails
        {
            get { return m_additionalEmails; }
            set { m_additionalEmails = value; }
        }
        #endregion

        #region InitializeFilter
        string _filter = string.Empty;

        [ConnectionConsumer("User Manager Filter Consumer", "UserManagerFilterConsumer")]
        public void InitializeFilter(IUserManagerFilter umFilter)
        {
            _filter = umFilter.SelectedFilter;
        }
        #endregion

        #region IUserManagerUserEditor Members
        private string _userToEdit = string.Empty;

        public string UserAccountToEdit
        {
            get { return _userToEdit; }
        }
        #endregion

        #region ConnectionProvider
        [ConnectionProvider("User Editor Provider", "UserManagerUserEditorProvider")]
        public IUserManagerUserEditor InitializeProvider()
        {
            return this as IUserManagerUserEditor;
        }
        #endregion

        #region UserManager
        private cUserManager _cUserManager;
        protected cUserManager UserManager
        {
            get
            {
                if (_cUserManager == null)
                    _cUserManager = new cUserManager(ConfigurationManager.ConnectionStrings["ADAMConnectionString"].ConnectionString);

                return _cUserManager;
            }
        }
        #endregion

        #region UserTable
        private DataTable UserTable
        {
            get
            {
                if (_filter == string.Empty)
                    _filter = "(CN=a*)";

                DataTable userTable = new UserDataTable(UserManager, string.Format("(&(objectCategory=user){0})", _filter));
                return userTable;
            }
        }
        #endregion

        private DataGrid m_displayGrid;
        private Label m_label;

        protected override void CreateChildControls()
        {
            m_label = new Label();
            m_displayGrid = new DataGrid();
            m_displayGrid.AutoGenerateColumns = false;
            m_displayGrid.Width = new Unit("100%");
            m_displayGrid.AlternatingItemStyle.CssClass = "ms-alternating";

            BoundColumn userId = new BoundColumn();
            userId.HeaderText = "User ID";
            userId.HeaderStyle.CssClass = "leftNav1";
            userId.DataField = UserDataTable.UserDataTableColumns.UserId.ToString();
            userId.ItemStyle.HorizontalAlign = HorizontalAlign.Center;
            m_displayGrid.Columns.Add(userId);

            BoundColumn firstName = new BoundColumn();
            firstName.HeaderText = "First";
            firstName.HeaderStyle.CssClass = "leftNav1";
            firstName.ItemStyle.HorizontalAlign = HorizontalAlign.Center;
            firstName.DataField = UserDataTable.UserDataTableColumns.FirstName.ToString();
            m_displayGrid.Columns.Add(firstName);

            BoundColumn lastName = new BoundColumn();
            lastName.HeaderText = "Last";
            lastName.HeaderStyle.CssClass = "leftNav1";
            lastName.DataField = UserDataTable.UserDataTableColumns.LastName.ToString();
            lastName.ItemStyle.HorizontalAlign = HorizontalAlign.Center;
            m_displayGrid.Columns.Add(lastName);

            BoundColumn companyName = new BoundColumn();
            companyName.HeaderText = "Service";
            companyName.HeaderStyle.CssClass = "leftNav1";
            companyName.DataField = UserDataTable.UserDataTableColumns.Service.ToString();
            companyName.ItemStyle.HorizontalAlign = HorizontalAlign.Center;
            m_displayGrid.Columns.Add(companyName);

            BoundColumn phoneNumber = new BoundColumn();
            phoneNumber.HeaderText = "Phone";
            phoneNumber.HeaderStyle.CssClass = "leftNav1";
            phoneNumber.DataField = UserDataTable.UserDataTableColumns.Phone.ToString();
            phoneNumber.ItemStyle.HorizontalAlign = HorizontalAlign.Center;
            m_displayGrid.Columns.Add(phoneNumber);

            BoundColumn requestor = new BoundColumn();
            requestor.HeaderText = "Requester";
            requestor.HeaderStyle.CssClass = "leftNav1";
            requestor.DataField = UserDataTable.UserDataTableColumns.Requester.ToString();
            requestor.ItemStyle.HorizontalAlign = HorizontalAlign.Center;
            m_displayGrid.Columns.Add(requestor);

            BoundColumn userEnabled = new BoundColumn();
            userEnabled.HeaderText = "Enabled";
            userEnabled.HeaderStyle.CssClass = "leftNav1";
            userEnabled.DataField = UserDataTable.UserDataTableColumns.Enabled.ToString();
            userEnabled.ItemStyle.HorizontalAlign = HorizontalAlign.Center;
            m_displayGrid.Columns.Add(userEnabled);

            ButtonColumn toggleEnabled = new ButtonColumn();
            toggleEnabled.HeaderText = "Enabled";
            toggleEnabled.HeaderStyle.CssClass = "leftNav1";
            toggleEnabled.Text = "Toggle";
            toggleEnabled.ItemStyle.HorizontalAlign = HorizontalAlign.Center;
            toggleEnabled.CommandName = "Toggle";
            m_displayGrid.Columns.Add(toggleEnabled);

            ButtonColumn resetPassword = new ButtonColumn();
            resetPassword.HeaderStyle.CssClass = "leftNav1";
            resetPassword.HeaderText = "Password";
            resetPassword.Text = "Reset";
            resetPassword.ItemStyle.HorizontalAlign = HorizontalAlign.Center;
            resetPassword.CommandName = "ResetPassword";
            m_displayGrid.Columns.Add(resetPassword);

            ButtonColumn modifyUser = new ButtonColumn();
            modifyUser.HeaderStyle.CssClass = "leftNav1";
            modifyUser.Text = "Modify";
            modifyUser.ItemStyle.HorizontalAlign = HorizontalAlign.Center;
            modifyUser.CommandName = "Modify";
            m_displayGrid.Columns.Add(modifyUser);

            ButtonColumn deleteUser = new ButtonColumn();
            deleteUser.HeaderStyle.CssClass = "leftNav1";
            deleteUser.Text = "Delete";
            deleteUser.ItemStyle.HorizontalAlign = HorizontalAlign.Center;
            deleteUser.CommandName = "Delete";
            m_displayGrid.Columns.Add(deleteUser);

            m_displayGrid.ItemCommand += new DataGridCommandEventHandler(HandleItemCommand);
            Controls.Add(m_label);
            Controls.Add(m_displayGrid);
        }

        void HandleItemCommand(object source, DataGridCommandEventArgs e)
        {
            string userId = e.Item.Cells[0].Text;
            DirectoryEntry user = null;
            SPSecurity.RunWithElevatedPrivileges(
                delegate()
                {
                    switch (((LinkButton)e.CommandSource).CommandName)
                    {
                        case "Toggle":
                            user = UserManager.FindUser(userId);
                            user.Properties["msDS-UserAccountDisabled"].Value = !(bool)user.Properties["msDS-UserAccountDisabled"].Value;
                            user.CommitChanges();

                            m_label.Text = "Account " + userId + " Disable State is: <i>" + user.Properties["msDS-UserAccountDisabled"].Value.ToString() + "</i>.";
                            break;
                        case "ResetPassword":
                            user = UserManager.FindUser(userId);
                            string email = user.Properties["mail"].Value.ToString();
                            string password = Membership.GeneratePassword(9, 2);
                            user.Options.PasswordPort = UserManager.Connection.Port();
                            user.Invoke("SetPassword", password);

                            if (SPUtility.SendEmail(SPContext.Current.Web, false, false, email, "Password Reset",
                                "<p>An administrator has reset your password.<br/>Your new password is: <b>" + password + "</b></p>"))
                            {
                                m_label.Text = "Account " + userId + " password reset successfully.  An e-mail was sent to their address <i>" + email + "</i>.";
                            }
                            else
                            {
                                m_label.Text = "Account " + userId + " password reset successfully, but an attempt to e-mail the user at <i>" + email + "</i> failed.<br/>"
                                    + "Please notify the user that their new password is: <b>" + password + "</b>";
                            }
                            break;
                        case "Delete":
                            UserManager.DeleteUser(userId);

                            m_label.Text = "Account " + userId + " has been deleted.";
                            break;
                        case "Modify":
                            _userToEdit = userId;
                            break;
                        default:
                            break;
                    }
                }
            );
        }

        protected override void OnPreRender(EventArgs e)
        {
            m_displayGrid.DataSource = UserTable;
            m_displayGrid.DataBind();

            base.OnPreRender(e);
        }

        
    }
}
